package com.shawn.baseappbygroovydsl.utils

import android.Manifest
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import com.kyle.calendarprovider.calendar.CalendarEvent
import com.kyle.calendarprovider.calendar.CalendarProviderManager
import com.permissionx.guolindev.PermissionX
import com.permissionx.guolindev.request.ExplainScope
import com.shawn.baseappbygroovydsl.R
import com.shawn.baseappbygroovydsl.ui.extension.ExtensionLog.log
import java.util.*
import kotlin.collections.ArrayList

/**
 * 描述：
 * 作者： shawn
 * 时间： 2024/6/1717:27
 */
object UtilCalendar {
    fun requestCalendarPermission(activityHome: AppCompatActivity, result: (Boolean) -> Unit) {
        val requestList = ArrayList<String>()
        requestList.add(Manifest.permission.WRITE_CALENDAR)
        requestList.add(Manifest.permission.READ_CALENDAR)
        PermissionX.init(activityHome)
            .permissions(requestList)
            .onExplainRequestReason { scope: ExplainScope, deniedList: List<String?>? ->
                val message = "签到提醒需要您同意以下权限才能正常使用"
                scope.showRequestReasonDialog(
                    deniedList as List<String>, message, "同意",
                    "拒绝"
                )
                "用户选择拒绝后不再请求 您拒绝了如下权限:$deniedList".log()
            }
            .request { allGranted: Boolean, grantedList: List<String?>?, deniedList: List<String?> ->
                if (allGranted) {
                    "日历权限申请通过".log()
                } else {
                    "您拒绝了如下权限:$deniedList".log()
                }
                result.invoke(allGranted)
            }
    }


    fun sendRemind(context: Context, callBack: (Int) -> Unit) {
        val list = arrayListOf<CalendarEvent>()
        list.add(getRemind(context, 18))
        // 添加事件
        val result = CalendarProviderManager.addCalendarEvent(context, list)
        callBack.invoke(result)
    }

    private fun getRemind(context: Context,hour:Int): CalendarEvent {
        val calendar = Calendar.getInstance()
        calendar[Calendar.HOUR_OF_DAY] = hour
        calendar[Calendar.MINUTE] = 0
        calendar[Calendar.SECOND] = 0

        val oneHour = 1000L * 60 * 60
        val startMillis = calendar.timeInMillis
        val endMillis = startMillis + oneHour

        val title = "[${context.getString(R.string.app_name)}]今天还有88元红包待领取，快去签到吧！"
        val desc = "连续签到可领取大额红包哦"
        return CalendarEvent(
            title,
            desc,
            "",
            startMillis,
            endMillis,
            0, "FREQ=DAILY;COUNT=7"
        )
    }
}